using System.Web;
using System.Web.UI;
using Kiwi.Container.DependencyInjection;

namespace Kiwi.Container.Web
{
    public class HttpHandlerDependencyInjector : IHttpHandlerDependencyInjector, IContainerExtension
    {
        public IEnumerateDependentProperties DependentProperties { get; set; }
        public bool ApplyToControls { get; set; }

        #region IHttpHandlerDependencyInjector Members

        public void InjectDependencies(IContainer container, IHttpHandler handler)
        {
            container.Inject(handler, DependentProperties);

            if (ApplyToControls)
            {
                var page = handler as Page;
                if (page != null)
                {
                    page.PreInit += (o, e) => InjectPageControlDependencies(page, container);
                }
            }
        }

        #endregion

        private void InjectPageControlDependencies(Control page, IComponentResolver container)
        {
            InjectControlDependencies(page.Controls, container);
        }

        private void InjectControlDependencies(ControlCollection controls, IComponentResolver container)
        {
            foreach (Control control in controls)
            {
                container.Inject(control, DependentProperties);
                InjectControlDependencies(control.Controls, container);
            }
        }
    }
}